package com.ding.controller;

import com.ding.bean.Department;
import com.ding.bean.Employee;
import com.ding.dao.DepartmentMapper;
import com.ding.dao.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * EmployeeController
 *
 * @author DYS
 * @date 2021/7/21
 * @time 12:05
 * @Description
 */
@Controller
public class EmployeeController {

	@Autowired
	EmployeeMapper employeeMapper;
	@Autowired
	DepartmentMapper departmentMapper;

	@RequestMapping("/employees")
	public String list(Model model){
		Collection<Employee> employees = employeeMapper.getAllEmployees();
		model.addAttribute("employees",employees);
		return "emp/list";
	}

	@GetMapping("/emp")
	public String toAddPage(Model model){
		//获取全部的部门
		Collection<Department> departments = departmentMapper.getAllDepartment();
		model.addAttribute("departments",departments);
		return "emp/add";
	}

	@PostMapping("/emp")
	public String toAddEmp(Employee employee){
		//添加的操作
		System.out.println(employee);
		employee.setEid(employee.getDepartment().getId());
		employeeMapper.addEmployee(employee);
		return "redirect:/employees";
	}

	//员工修改
	@GetMapping("/emp/{id}")
	public String toUpdateEmp(@PathVariable("id") Integer id,Model model){
		Employee employee = employeeMapper.getEmployeeById(id);
		Collection<Department> departments = departmentMapper.getAllDepartment();
		model.addAttribute("departments",departments);
		model.addAttribute("emp",employee);
		return "emp/update";
	}

	//对提交的员工修改进行处理
	@RequestMapping("/updateEmp")
	public String updateEmp(HttpServletRequest req){
		//如果使用BeanUtils就需要导入一个依赖，
		// 然后用req.getParameterMap()获取map集合，
		// 接着使用BeanUtils里面的populate方法进行封装。。在这里不使用
		int id = Integer.parseInt(req.getParameter("id"));
		String lastName = req.getParameter("lastName");
		String email = req.getParameter("email");
		int gender = Integer.parseInt(req.getParameter("gender"));
		int departmentId = Integer.parseInt(req.getParameter("department.id"));
		Department department = departmentMapper.getDepartmentById(departmentId);
		String birth = req.getParameter("birth");
		Integer eid = department.getId();
		Employee employee = new Employee(id,lastName,email,gender,birth,eid);
		employeeMapper.updEmployee(employee);
		return "redirect:/employees";
	}

	//删除员工
	@GetMapping("/delEmp/{id}")
	public String delEmp(@PathVariable("id") int id){
		employeeMapper.delEmployee(id);
		return "redirect:/employees";
	}
	//404错误处理，springboot会默认找到error下的404.html进行处理
}
